
package com.netease.xone.fragment;

import java.util.ArrayList;
import java.util.List;

import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.meta.FilterInfo;
import protocol.meta.Subject;
import protocol.meta.User;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.TextView.BufferType;

import com.handmark.pulltorefresh.library.X1LoadingAdapterViewBase.OnLoadingListener;
import com.netease.pkgRelated.XoneConsts;
import com.netease.xone.R;
import com.netease.xone.activity.ActivityModifyFindCondition;
import com.netease.xone.adapter.FindFriendsAdapter;
import com.netease.xone.widget.listview.LoadingListView;

public class FragmentFindFriends extends FragmentBase {

    public enum FindFrindsType {
        guess_you_like, popularity_list// 猜你喜欢，人气榜
    }

    public static int REQUEST_CODE = 0x01;

    public static Fragment newInstance(FindFrindsType type) {
        Fragment f = new FragmentFindFriends();
        Bundle b = new Bundle();
        b.putSerializable(XoneConsts.BUNDLE_KEY.FIND_FRINEDS_TYPE, type);
        f.setArguments(b);
        return f;
    }

    private FindFrindsType mType;
    private TextView mModifyCondition;
    private LoadingListView mList;
    private FindFriendsAdapter mAdapter;
    // Tid
    private int mTid;
    // Data
    private FilterInfo mFilterInfo;
    private List<User> mUserListAll;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        mType = (FindFrindsType)getArguments().getSerializable(
                XoneConsts.BUNDLE_KEY.FIND_FRINEDS_TYPE);
        XoneService.getInstance().addListener(mCallBack);
        mFilterInfo = new FilterInfo();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_find_friends, null);
        mModifyCondition = (TextView)v.findViewById(R.id.modify_condition);
        mModifyCondition.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), ActivityModifyFindCondition.class);
                i.putExtra(XoneConsts.BUNDLE_KEY.FIND_FRIENDS_FILTER, mFilterInfo);
                startActivityForResult(i, REQUEST_CODE);
            }
        });
        mList = (LoadingListView)v.findViewById(R.id.loading_list);
        mList.disablePullToRefresh();
        mAdapter = new FindFriendsAdapter(getActivity());
        mList.setAdapter(mAdapter);
        mList.setOnLoadingListener(new OnLoadingListener() {

            @Override
            public void onRefreshing() {

            }

            @Override
            public void onLoading() {
                switch (mType) {
                    case guess_you_like:
                        mTid = XoneService.getInstance().doGetGuessFriendList(1,
                                XoneConsts.LIST_ITEM_COUNT.SQUARE_REQUEST_COUNT);
                        break;
                    case popularity_list:
                        mTid = XoneService.getInstance().doGetPopFriendList(1,
                                XoneConsts.LIST_ITEM_COUNT.SQUARE_REQUEST_COUNT);
                        break;
                }
            }

            @Override
            public void onLoadingMore() {

            }
        });
        mList.load();
        return v;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        XoneService.getInstance().removeListener(mCallBack);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                mFilterInfo = data.getParcelableExtra(XoneConsts.BUNDLE_KEY.FIND_FRIENDS_FILTER);
                if (mFilterInfo.gender != -1
                        || (!TextUtils.isEmpty(mFilterInfo.province) && !mFilterInfo.province
                                .equals(getString(R.string.filter_condition_unlimited)))
                        || (!TextUtils.isEmpty(mFilterInfo.city) && !mFilterInfo.city
                                .equals(getString(R.string.filter_condition_unlimited)))
                        || mFilterInfo.userType != -1 || mFilterInfo.gameFilter
                        && mFilterInfo.subjectIdList != null
                        && mFilterInfo.subjectIdList.size() != 0) {
                    // 设置筛选条件的文本
                    StringBuilder sb = new StringBuilder(getString(R.string.recomm_for_you));
                    if (!TextUtils.isEmpty(mFilterInfo.city)
                            && !mFilterInfo.city
                                    .equals(getString(R.string.filter_condition_unlimited))) {
                        sb.append(" ").append(mFilterInfo.city);
                    } else if (!TextUtils.isEmpty(mFilterInfo.province)
                            && !mFilterInfo.province
                                    .equals(getString(R.string.filter_condition_unlimited))) {
                        sb.append(" ").append(mFilterInfo.province);
                    }

                    if (mFilterInfo.userType == 0) {
                        // 未认证
                        sb.append(" ").append(getString(R.string.filter_result_unauthenticated));
                    } else if (mFilterInfo.userType == 1) {
                        // 认证
                        sb.append(" ").append(getString(R.string.filter_result_authenticated));
                    }
                    if (mFilterInfo.gender == 1) {
                        sb.append(" ").append(getString(R.string.male));
                    } else if (mFilterInfo.gender == 2) {
                        sb.append(" ").append(getString(R.string.female));
                    }
                    if (mFilterInfo.gameFilter && mFilterInfo.subjectIdList != null
                            && mFilterInfo.subjectIdList.size() != 0) {
                        sb.append(" ").append(getString(R.string.game_player));
                    } else {
                        sb.append(" ").append(getString(R.string.user));
                    }
                    mModifyCondition.setText(sb.toString(), BufferType.SPANNABLE);
                    Spannable span = (Spannable)mModifyCondition.getText();
                    int start = getString(R.string.recomm_for_you).length();
                    int end = span.length();
                    span.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.blue)),
                            start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                } else {
                    mModifyCondition.setText(R.string.modify_search_condition);
                }
                // 开始筛选
                List<User> filterUsers = new ArrayList<User>();
                for (User user : mUserListAll) {
                    if (mFilterInfo.gender != -1 && user.gender != mFilterInfo.gender) {
                        continue;
                    }
                    String unLimitied = getString(R.string.filter_condition_unlimited);
                    if (!TextUtils.isEmpty(mFilterInfo.city)
                            && !mFilterInfo.city.equals(unLimitied)) {
                        if (!mFilterInfo.city.equals(user.city)) {
                            continue;
                        }
                    } else if (!TextUtils.isEmpty(mFilterInfo.province)
                            && !mFilterInfo.province.equals(unLimitied)) {
                        if (!mFilterInfo.province.equals(user.province)) {
                            continue;
                        }
                    }
                    if (mFilterInfo.userType != -1 && user.userType != mFilterInfo.userType) {
                        continue;
                    }
                    if (mFilterInfo.gameFilter && mFilterInfo.subjectIdList != null
                            && mFilterInfo.subjectIdList.size() != 0) {
                        boolean found = false;
                        for (String filterGameName : mFilterInfo.subjectIdList) {
                            for (Subject userGame : user.subjectList) {
                                if (filterGameName.equals(userGame.subjectName)) {
                                    filterUsers.add(user);
                                    found = true;
                                    break;
                                }
                            }
                            if(found)break;
                        }
                    } else {
                        filterUsers.add(user);
                    }
                }
                mAdapter.clear();
                if (filterUsers.size() != 0) {
                    mAdapter.addTail(filterUsers);
                    mAdapter.notifyDataSetChanged();
                    mList.onLoadingComplete(false);
                } else {
                    mList.onNoContent(getString(R.string.success_find_frinends_no_content));
                }
            }
        }
    }

    private XoneCallBack mCallBack = new XoneCallBack() {

        @Override
        public void onGetGuessFriendsList(int transactionId,
                java.util.List<protocol.meta.User> userList) {
            if (mTid == transactionId) {
                mUserListAll = userList;
                if (userList != null && userList.size() != 0) {
                    mList.onLoadingComplete(false);
                    mAdapter.addTail(userList);
                } else {
                    mList.onNoContent(getString(R.string.success_find_frinends_no_content));
                }
            }
        };

        @Override
        public void onGetGuessFriendsListError(int transactionId, int errCode, String err) {
            if (mTid == transactionId) {
                mList.onLoadingError();
            }
        };

        @Override
        public void onGetPopFriendsList(int transactionId, List<User> userList) {
            if (mTid == transactionId) {
                mUserListAll = userList;
                if (userList != null && userList.size() != 0) {
                    mList.onLoadingComplete(false);
                    mAdapter.addTail(userList);
                } else {
                    mList.onNoContent(getString(R.string.success_find_frinends_no_content));
                }
            }
        };

        @Override
        public void onGetPopFriendsListError(int transactionId, int errCode, String err) {
            if (mTid == transactionId) {
                mList.onLoadingError();
            }
        };

        @Override
        public void onFollow(int transactionId, String userId) {
            for (int i = 0; i < mAdapter.getCount(); i++) {
                User user = mAdapter.getItem(i);
                if (user.userId == userId) {
                    user.follow = 1;
                    mAdapter.notifyDataSetChanged();
                    break;
                }
            }
        };

        @Override
        public void onCancelFollow(int transactionId, String userId) {
            for (int i = 0; i < mAdapter.getCount(); i++) {
                User user = mAdapter.getItem(i);
                if (user.userId == userId) {
                    user.follow = 0;
                    mAdapter.notifyDataSetChanged();
                    break;
                }
            }
        };
    };
}
